<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>帖子发布测试 - jQuery版</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], textarea, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        textarea {
            height: 100px;
            resize: vertical;
        }
        .btn {
            background-color: #673ab7;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn:hover {
            background-color: #5e35b1;
        }
        #filePreview {
            margin-top: 10px;
            max-width: 200px;
            max-height: 200px;
        }
        #response {
            margin-top: 20px;
            padding: 10px;
            border-radius: 4px;
            background-color: #f0f0f0;
        }
        .progress {
            width: 100%;
            background: #f0f0f0;
            margin-top: 10px;
            display: none;
        }
        .progress-bar {
            height: 20px;
            background: #4CAF50;
            width: 0%;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>帖子发布测试</h1>

    <div class="form-group">
        <label for="username">用户名:</label>
        <input type="text" id="username" value="testuser">
    </div>

    <div class="form-group">
        <label for="accountId">账号ID:</label>
        <input type="text" id="accountId" value="1">
    </div>

    <div class="form-group">
        <label for="plateId">板块ID:</label>
        <input type="text" id="plateId" value="1">
    </div>

    <div class="form-group">
        <label for="title">帖子标题:</label>
        <input type="text" id="title" value="测试帖子标题">
    </div>

    <div class="form-group">
        <label for="content">帖子内容:</label>
        <textarea id="content">这是测试帖子的内容</textarea>
    </div>

    <div class="form-group">
        <label for="mediaType">媒体类型:</label>
        <select id="mediaType">
            <option value="1">图片</option>
            <option value="2">视频</option>
        </select>
    </div>

    <div class="form-group">
        <label for="location">位置信息:</label>
        <input type="text" id="location" value="北京市海淀区">
    </div>

    <div class="form-group">
        <label for="files">上传文件:</label>
        <input type="file" id="files" multiple>
        <div id="filePreview"></div>
    </div>

    <div class="progress">
        <div class="progress-bar"></div>
    </div>

    <div>
        <button class="btn" id="submitBtn">提交</button>
        <button class="btn" id="resetBtn">重置</button>
    </div>

    <div id="response"></div>
</div>

<!-- 引入jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://unpkg.com/dayjs"></script>
<script>
    $(document).ready(function() {
        // 文件预览
        $('#files').change(function(e) {
            $('#filePreview').empty();

            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    $('#filePreview').append($('<img>').attr('src', e.target.result));
                }
                reader.readAsDataURL(this.files[0]);
            }
        });

        // 提交按钮点击事件（关键改进）
        $('#submitBtn').click(function() {
            const username = $('#username').val();
            const files = $('#files')[0].files;

            // 构建postDTO对象（保持原结构）
            const postDTO = {
                post: {
                    accountId: parseInt($('#accountId').val()),
                    plateId: parseInt($('#plateId').val()),
                    title: $('#title').val(),
                    content: $('#content').val(),
                    isAudited: 1,
                    isDeleted: false,
                    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
                },
                postMedia: {
                    mediaType: parseInt($('#mediaType').val()),
                    url: null
                },
                postLocation: {
                    location: "116.30651,39.97708101",
                    locationName: $('#location').val()
                }
            };

            // 创建FormData对象（关键修改）
            const formData = new FormData();
            const blob = new Blob([JSON.stringify(postDTO)], {type: "application/json"});
            formData.append("postDTO", blob);  // 使用Blob包装JSON数据
            formData.append('username', username);

            // 文件验证（新增）
            const MAX_SIZE = 10 * 1024 * 1024; // 10MB限制
            const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'video/mp4'];

            for (let i = 0; i < files.length; i++) {
                if (files[i].size > MAX_SIZE) {
                    return alert(`文件${files[i].name}超过大小限制`);
                }
                if (!ALLOWED_TYPES.includes(files[i].type)) {
                    return alert(`文件${files[i].name}类型不支持`);
                }
                formData.append('files', files[i]);
            }

            // 上传进度处理（优化）
            $('.progress').show().css('background-color', '#f0f0f0');

            // AJAX请求（保持原结构）
            $.ajax({
                url: 'http://localhost:8081' +
                    '' +
                    '' +
                    '/addPost',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhr: function() {
                    const xhr = new XMLHttpRequest();
                    xhr.upload.addEventListener('progress', function(e) {
                        if (e.lengthComputable) {
                            const percent = Math.round((e.loaded / e.total) * 100);
                            $('.progress-bar')
                                .css('width', percent + '%')
                                .text(percent + '%');
                        }
                    }, false);
                    return xhr;
                },
                success: function(response) {
                    $('#response').html(`<strong>成功:</strong> ${JSON.stringify(response)}`)
                        .css('color', 'green');
                },
                error: function(xhr) {
                    const errorMsg = xhr.responseJSON?.message || xhr.responseText || '请求失败';
                    $('#response').html(`<strong>错误:</strong> ${errorMsg}`)
                        .css('color', 'red');
                },
                complete: function() {
                    setTimeout(() => $('.progress').hide(), 1000);
                }
            });
        });

        // 重置按钮
        $('#resetBtn').click(function() {
            $('#response').empty();
        });
    });
</script>
</body>
</html>